package com.ming.attendance.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ming.attendance.mapper.WxUserMapper;
import com.ming.attendance.model.UserInfoModel;
import com.ming.attendance.model.WxUserTokenModel;
import com.ming.attendance.po.EventUser;
import com.ming.attendance.po.ResponseBean;
import com.ming.attendance.po.WxUser;
import com.ming.attendance.service.WxUserService;
import com.ming.attendance.utils.DecryptUtil;
import com.ming.attendance.utils.JWTUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WxUserServiceImpl implements WxUserService {
    @Autowired
    private WxUserMapper um;

    @Override
    public ResponseBean<Integer> createUser(WxUser user) {
        int result = 0;
        result = um.createUser(user);
        if(result != 0 ){
            return new ResponseBean<>(result);
        }else{
            return new ResponseBean<>(602,"创建失败");
        }
    }

    @Override
    public ResponseBean<UserInfoModel> getUserInfo(String openid) {
        UserInfoModel result = new UserInfoModel();
        WxUser user = um.getUser(openid);
        List<EventUser> list = user.getEventUsers();
        float checkedNumber = 0;
        int joinNumber = 0;
        int managerNumber = 0;
        for (EventUser eventUser : list) {
            if(eventUser.getIdentity()==1){             // 管理的
                managerNumber++;
            }else{                                      // 加入的
                if(eventUser.getIsChecked()==1){        // 出勤的
                    checkedNumber++;
                }
                joinNumber++;
            }
        }
        // 除掉eventUsers相关数据
        user.setEventUsers(null);
        result.setUser(user);
        result.setCheckedNumber((int) checkedNumber);
        result.setJoinNumber(joinNumber);
        result.setManagerNumber(managerNumber);
        result.setAttendanceRate(Double.parseDouble(String.format("%.4f",checkedNumber/joinNumber)));

        if(user!=null){
            return new ResponseBean<>(result);
        }else{
            return new ResponseBean<>(601,"没有该用户");
        }
    }

    @Override
    public ResponseBean<Integer> updateUser(WxUser user) {
        int result = um.updateUser(user);
        if(result!=0){
            return new ResponseBean<>(result);
        }else{
            return new ResponseBean<>(603,"更改失败");
        }
    }

    @Override
    public ResponseBean<WxUserTokenModel> login(WxUser user) {

        // 验证用户信息
        // if(!StringUtils.isEmpty(user.getOpenid()) && !StringUtils.isEmpty(user.getSessionKey())){
        if(!StringUtils.isEmpty(user.getOpenid())){
            WxUser tempUser = um.getUser(user.getOpenid());
            // 判断数据库中是否存在该openid用户
            if(tempUser!=null){
                // 若数据库中有该用户，则更新session_key和上次登录时间信息
                user.setLastTime(String.valueOf(new Date().getTime()));
                um.updateUser(user);
            }else{
                // 若数据库中没有该用户，则添加用户到数据库中
                user.setUuid(UUID.randomUUID().toString());
                user.setCreateTime(String.valueOf(new Date().getTime()));
                user.setLastTime(String.valueOf(new Date().getTime()));
                um.createUser(user);
            }
            // 获取token
            String token = JWTUtils.getToken(user);

            // 封装响应数据
            WxUserTokenModel model = new WxUserTokenModel();
            // model.setUuid(user.getUuid());
            // model.setOpenid(user.getOpenid());
            // model.setSessionKey(user.getSessionKey());
            model.setToken(token);
            return new ResponseBean<>(model); // 返回创建好的用户信息

        }else{  // 微信服务器没有返回正确的openid
            return new ResponseBean<>(700,"微信服务器问题");
        }
    }

    @Override
    public ResponseBean<Object> getDecryptedData(String sessionKey,String encryptedData, String iv) {
        System.out.println("encryptedData: >>>>> " + encryptedData);
        System.out.println("iv: >>>>> " + iv);
        System.out.println("session_key: >>>>> " + sessionKey);
        String result = DecryptUtil.decryptWxDataOfHutool(encryptedData, sessionKey, iv);

        System.out.println("解密结果: >>>>>>  "+result);
        return new ResponseBean<>(JSON.parse(result));
    }

}
